import pandas as pd
import numpy as np
from sklearn.model_selection import KFold
from sklearn.linear_model import LinearRegression


df = pd.read_csv(r'C:\Users\Wang\Desktop\data\2.csv')#exchange	stock_symbol	date	stock_price_open	stock_price_high	stock_price_low	stock_volume	label

X=df.iloc[:,[4,5,6]]#自变量
y=df.iloc[:,7]#因变量
X = np.array(X)
y = np.array(y)
df = df.sort_values(by='date', ascending=True)  # 升序排列
kf = KFold(n_splits=10,shuffle=True,random_state=1)#K折交叉验证，K=10
d=np.zeros((10,1))#用于计算准确率.精确率和召回率的数组
e=np.zeros((10,1))
f=np.zeros((10,1))
j1=0
j2=0
j3=0
for train_index, test_index in kf.split(X,y):
    X_train = X[train_index,:]#按照K折交叉，划分测试集和训练集
    X_test= X[test_index,:]
    y_train = y[train_index]
    y_test= y[test_index]
    clf = LinearRegression(n_jobs=-1)# 生成scikit-learn的线性回归对象
    clf.fit(X_train, y_train)# 开始训练
    forecast= clf.predict(X_test)# 进行预测

    c=len(y_test)
    i1 =0# 使用for循环和if判定，判断预测值和测试集结果是否同号，即准确率
    for k1 in range(0, c):
        a = y_test[k1]
        b = forecast[k1]
        if (a==1 and b>0)or(a==0 and b<0):
            i1=i1+1
    d[j1][0] = round(i1 / c, 3)
    j1 = j1 + 1

    i2 = 0  # 精确率
    l2 = 0
    for k2 in range(0, c):
        a = y_test[k2]
        b = forecast[k2]
        if (a == 1 and b > 0) :
            i2 = i2 + 1
        if (b>0):
            l2=l2+1
    e[j2][0] = round(i2 / l2, 3)
    j2 = j2 + 1

    i3 = 0  # 召回率
    l3 = 0
    for k3 in range(0, c):
        a = y_test[k3]
        b = forecast[k3]
        if (a == 1 and b > 0):
            i3 = i3 + 1
        if (a==1):
            l3 = l3 + 1
    f[j3][0] = round(i3 / l3, 3)
    j3 = j3 + 1
print('准确率：')
print(np.mean(d, axis=0))
print('精确率：')
pres=np.mean(e, axis=0)
print(pres)
print('召回率：')
recall=np.mean(f, axis=0)
print(recall)
F1=(2*pres*recall)/(pres+recall)
print('F1-score：')
print(F1)
